package com.xh.bussiness.thirdapi.feihong.util;

import org.springframework.util.StringUtils;

import java.security.MessageDigest;
import java.util.*;

/**
 * 飞鸿业务系统加密工具类
 */
public class FeiHongMd5Util {

    /**
     * 获取MD5字符
     *
     * @param s
     * @return
     */
    public final static String getMD5(String s) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] strTemp = s.getBytes();
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }


    public static String geturlstr(Map<String, String> parameters, String accesskey) {

        List<String> list = new ArrayList<>();
        Iterator<String> iterator = parameters.keySet().iterator();

        // 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起
        StringBuilder basestring = new StringBuilder();

        while (iterator.hasNext()) {
            String key = iterator.next();
            list.add(key);
        }
        Collections.sort(list);
        for (String key : list){
            String value = parameters.get(key);
            if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(value)){
                basestring.append(key).append("=").append(value).append("&");
            } else if (!StringUtils.isEmpty(key)){
                basestring.append(key);
            }
        }
        basestring.append("key=").append(accesskey);
        return basestring.toString();
    }



    /**
     * 32位进制-大写
     *
     * @param s
     * @return
     */
    public final static String getmd5sign(String s) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        try {
            byte[] strTemp = s.getBytes();
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }

    }
}
